package main

import (
	"fmt"
	"net"
	"strings"
)

var onlineClients = make(map[string]net.Conn)

func broadCast(publisher string,context string){
		//循环所有的客户端
		for _,client := range onlineClients{
			//将发送的内容进行返回
			client.Write([]byte(publisher + ":" + context))
		}
}

func read(conn net.Conn, addr string){
	for {
		data := make([]byte,1024)
		n,_:=conn.Read(data)

		if string(data[:n]) == "" {
			//下线操作
			delete(onlineClients,addr)
			broadCast("系统消息：",addr+"已经下线")
			return
		}

		content := strings.TrimSpace(string(data[:n]))
		fmt.Println("读取客户端发的内容::",content)
	
		broadCast(addr,content)
		// //循环所有的客户端
		// for ip,client := range onlineClients{
		// 	//将发送的内容进行返回
		// 	client.Write([]byte(ip + ":" + string(data[:n])))
		// }
	}
}

func main() {
	listen,_ := net.Listen("tcp","127.0.0.1:8080")
	for {
		conn,_:=listen.Accept()
		fmt.Println("连接的con::",conn)
		//获取客户端的IP
		addr := conn.RemoteAddr().String()
		fmt.Printf("来自客户端【%s】的连接\n",addr)
		onlineClients[addr] = conn
	
		broadCast("系统消息：",addr+"已经上线")
		go read(conn,addr)
	}

}